package cn.fengLone.pay.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.fengLone.pay.service.WeiXinNotifyService;

/**
 * 
 * 微信支付支付结果异步回调
 * 
 * @author Guo Pengfei
 * 
 * @compony 深圳风轮科技有限公司
 * 
 * @date 2017-07-20
 * 
 */
@Controller
@RequestMapping("/wechatPayNotify")
public class WeiXinNotifyController {
	private Logger logger = Logger.getLogger(WeiXinNotifyController.class);

	@Resource
	private WeiXinNotifyService weiXinNotifyService;
	/**
	 * 订单支付结果通知
	 * @param request
	 * @return
	 */
	@RequestMapping("/asynNotify")
	@ResponseBody
	public String NotifyUrl(HttpServletRequest request,HttpServletResponse response) {
		String xmlData =null;
		try {
			xmlData = convertStreamToString(request.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("获取微信返回的支付结果:\n"+xmlData+"\n出现错误!");
			return "FAIL";
		}
		String result = null;
		try {
			result = weiXinNotifyService.wechatNotify(xmlData);
		} catch (Exception e) {
			result = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA["+e.getMessage()+"]]></return_msg></xml>";
		}
		return result;
	}
	
	/**
	 * 将InputStream转为String To convert the InputStream to String we use the
	 * BufferedReader.readLine() method. We iterate until the BufferedReader
	 * return null which means there's no more data to read. Each line will
	 * appended to a StringBuilder and returned as String.
	 * 
	 * @param is
	 * @return
	 */
	private String convertStreamToString(InputStream is) {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}
}
